<template>
  <div style="padding: 20px">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>首页>课程管理>题库管理</span>
        <br>
        <br>
        <el-button type="primary" size="mini" @click="downloadMedel()">下载题目模板</el-button>
        <el-button type="success" size="mini" @click="handleCreate()">添加</el-button>
        <el-button type="success" size="mini" @click="queryCourse()">查看课程</el-button>
        <el-upload
          style="width: 90px;float: left;"
          :headers="headers"
          :data="exceldata"
          :on-success="onSuccess"
          :on-error="onError"
          :show-file-list="false"
          :action="uploadPathList"
          :on-change="handleChange">
          <el-button size="mini" type="primary">导入题目</el-button>
        </el-upload>
      </div>
      <!--<div v-for="o in list" :key="o" class="text item">-->
      <!--{{'列表内容 ' + o.questionName }}-->
      <!--</div>-->
      <div
        v-for="(tag,index) in list"
        :key="tag.id"
        class="text item">
        <!--{{ tag.serialNumber+"."+ tag.questionName }}-->
        {{ tag.questionName }}

        <el-button type="primary" size="mini" @click="handleUpdate(tag)">编辑</el-button>
        <el-button type="danger" size="mini" @click="handleDelete(tag)">删除</el-button>
        <br>
        <div
          v-for="(tag1) in list[index].adminQuestionAnswerDTOList"
          :key="tag1.id"
          :class="tag.correct==tag1.title?'text text1 item':'text item'"
        >
          {{ tag1.title+"."+ tag1.content }}
        </div>
        <!-- <div
          v-for="(tag2) in list[index].adminQuestionAnswerDTOList"
          :key="tag2.id"
          class="text item"
        >
          {{ tag2.title+"."+ tag2.content }}
        </div> -->
        <br>
      </div>
    </el-card>

    <!-- 基本设置 -->
    <el-dialog :title="textMap[dialogStatus]" :close-on-click-modal="false" :visible.sync="dialogFormVisible" >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 80%; margin-left:50px;"
      >
        <!--<el-form-item label="序号" prop="serialNumber">-->
          <!--<el-input v-model="dataForm.serialNumber" placeholder="请输入序号" type="number"/>-->
        <!--</el-form-item>-->
        <el-form-item label="题干" prop="questionName">
          <el-input v-model="dataForm.questionName" placeholder="请输入题干"/>
        </el-form-item>
        <!--<el-form-item label="分数" prop="score">-->
          <!--<el-input v-model="dataForm.score" placeholder="请输入分值" type="number"/>-->
        <!--</el-form-item>-->
        <el-form-item label="正确答案" prop="correct">
          <el-select v-model="dataForm.correct" placeholder="请选择正确答案">
            <el-option label="A" value="A"/>
            <el-option label="B" value="B"/>
            <el-option label="C" value="C"/>
            <el-option label="D" value="D"/>
          </el-select>
        </el-form-item>
        <el-form-item label="答案选择">
          <el-table
            :data="dataForm.adminQuestionAnswerDTOList"
            style="width: 100%">
            <el-table-column
              prop="title"
              label="标题"
              width="50"/>
            <el-table-column
              prop="content"
              label="内容"
              width="300">
              <template slot-scope="scope">
                <el-input v-model="scope.row.content"/>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">取消</el-button>
        <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button size="mini" v-else type="primary" @click="updateData">确定</el-button>
        <el-button size="mini" v-if="dialogStatus=='create'" type="success" @click="createNextData">确定并添加下一题</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .constant {
    width: 100%;
  }

  .img {
    margin-top: 20px;
    width: 150px;
    height: 150px;
  }

  .img img {
    width: 100%;
    height: 100%;
  }

  .list {
    width: 100%;
  }

  .list-cell {
    width: 100%;
    line-height: 50px;
  }

  .cell {
    width: 100%;
    /*display: inline-flex;*/
  }

  .set {
    color: deepskyblue;
  }

  .line {
    width: 100%;
    border-bottom: 2px solid #f6f6f6;
  }

  .erweima {
    width: 100%;
    border-bottom: 2px solid #f6f6f6;
  }
  .text {
    font-size: 14px;
  }
  .text1{
    text-shadow:5px 2px 6px green;
  }
  .item {
    margin-top: 10px;
  }

</style>

<script>
import { listQuestion, updateQuestion, createQuestion, createList } from '@/api/question'
import { uploadPath, uploadPathList } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import TagsView from '../layout/components/TagsView' // Secondary package based on el-pagination

export default {
  name: 'StoreSet',
  components: { TagsView, Pagination },
  data() {
    return {
      uploadPathList,
      uploadPath,
      fileList: [],
      courseId: undefined,
      courseType: undefined,
      associatedIndustryId: undefined,
      questionAnswerList: [{
        id: undefined,
        examQuestionId: undefined,
        title: undefined,
        content: undefined
      }],
      list: undefined,
      listLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      listQuery: {
        id: undefined,
        page: 1,
        limit: 100000,
        courseId: this.courseId,
        questionName: undefined,
        sort: 'serial_number',
        order: 'asc'
      },
      rules: {
        serialNumber: [
          { required: true, message: '序号不能为空', trigger: 'blur' }
        ],
        questionName: [
          { required: true, message: '题干不能为空', trigger: 'blur' }
        ],
        score: [
          { required: true, message: '分数不能为空', trigger: 'blur' }
        ],
        correct: [
          { required: true, message: '正确答案不能为空', trigger: 'blur' }
        ]
      },
      exceldata: {
        objectId: this.courseId
      },
      downloadLoading: false,
      dataForm: {
        id: undefined,
        courseId: this.courseId,
        courseType: undefined,
        serialNumber: undefined,
        questionName: undefined,
        score: undefined,
        correct: '',
        deleteMark: undefined,
        createDate: undefined,
        adminQuestionAnswerDTOList: [{ title: 'A', content: '' }, { title: 'B', content: '' }, { title: 'C', content: '' }, { title: 'D', content: '' }]
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          courseId: this.courseId,
          courseType: undefined,
          serialNumber: undefined,
          questionName: undefined,
          score: undefined,
          correct: undefined,
          deleteMark: undefined,
          createDate: undefined,
          adminQuestionAnswerDTOList: [{ title: 'A', content: '' }, { title: 'B', content: '' }, { title: 'C', content: '' }, { title: 'D', content: '' }]
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.init()
    this.courseId = this.$route.query.courseId
    this.exceldata.objectId = this.$route.query.courseId
  },
  methods: {
    downloadMedel () {
      window.location.href = 'http://mdadmin.rl716.com/mdtikudowm/tiku.xlsx'
    },
    onError (e) {
      console.log(e)
    },
    onSuccess (e) {
      console.log(e)
      if (e.code === 200) {
        this.init()
        this.$notify.success({
          title: '成功',
          message: '导入题目成功'
        })
      }
    },
    handleChange (e) {
      console.log(e)
    },
    queryCourse() {
      this.$router.push({ path: '/courseManage/queryCourse', query: { associatedIndustryId: this.associatedIndustryId,courseId: this.list.id, courseType: this.courseType }})
    },
    uploadPicUrl: function(response) {
      this.dataForm.picUrl = response.data.url
    },
    init: function() {
      if (this.$route.query.courseId == null) {
        return
      }
      if (this.$route.query.courseType!=null||this.$route.query.courseType!=undefined) {
        this.courseType = this.$route.query.courseType
      }
      if (this.$route.query.associatedIndustryId!=null||this.$route.query.associatedIndustryId!=undefined) {
        this.associatedIndustryId = this.$route.query.associatedIndustryId
      }
      this.courseId = this.$route.query.courseId
      this.listQuery.courseId = this.courseId
      this.getList()
    },
    getList() {
      this.listLoading = true
      listQuestion(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          // this.questionAnswerList = []
          // for (var i = 0; i < this.list .length; i++) {
          //   // console.log(i)
          //   // console.log(this.list[i].adminQuestionAnswerDTOList)
          //   for (var j = 0; j < this.list[i].adminQuestionAnswerDTOList .length;  j++){
          //     console.log(this.list[i].adminQuestionAnswerDTOList[j].title)
          //   }
          // }
          this.listLoading = false
        })
        .catch(() => {
          this.list = undefined
          this.listLoading = false
        })
    },
    handleUpdate(tag) {
      this.dataForm = Object.assign({}, tag)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateQuestion(this.dataForm)
            .then(() => {
              // for (const v of this.list) {
              //   if (v.id === this.dataForm.id) {
              //     const index = this.list.indexOf(v)
              //     this.list.splice(index, 1, this.dataForm)
              //     break
              //   }
              // }
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createQuestion(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    createNextData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createQuestion(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.getList()
              this.handleCreate()
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.message
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.dataForm = Object.assign({}, row)
      this.dataForm.deleteMark = 1
      this.$confirm('此操作将逻辑删除题库, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateQuestion(this.dataForm)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.message
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>
